package com.finger.gulimall.cart.interceptor;

import com.finger.common.constant.AuthConstant;
import com.finger.common.constant.CartConstant;
import com.finger.common.constant.CommonConstant;
import com.finger.common.vo.MemberVo;
import com.finger.gulimall.cart.to.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartCookieInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getIsTempUser()){
            // 如果前置处理器接收到name为user-key的cookie，说明一直登录过，这里就不会进来，能进来的说明第一次进购物车
            // 创建购物车cookie
            Cookie cookie = new Cookie(CartConstant.USER_KEY, userInfoTo.getUserKey());
            // 设置cookie作用范围
            cookie.setDomain(CommonConstant.SESSION_COOKIE_DEMAIN_AREA);
            // 设置cookie的存活时间，一天
            cookie.setMaxAge(CartConstant.USER_KEY_MAXAGE);
            resp.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 释放本地线程
        threadLocal.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        HttpSession session = req.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        // 从会话域中获取登录的用户
        MemberVo loginMember = (MemberVo) session.getAttribute(AuthConstant.LOGIN_MEMBER);

        if (loginMember != null) {
            // 如果用户登录，设置用户id
            userInfoTo.setUserId(loginMember.getId());
        }
        // 遍历前端的每个cookie
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.USER_KEY.equals(cookie.getName())) {
                    // 拿到user-key的值
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTempUser(true);
                }
            }
        }

        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            // 如果user-key为空，说明是第一次，生成user-key
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        // 线程本地化，Map<Thread,Object>
        threadLocal.set(userInfoTo);
        return true;
    }
}
